package cn.iocoder.yudao.module.cmt.service.course;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.course.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.course.CourseLearnRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.course.CourseLearnRecordMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class CourseLearnRecordServiceImpl implements CourseLearnRecordService {

    @Resource
    private CourseLearnRecordMapper courseLearnRecordMapper;

    @Override
    public Long createCourseLearnRecord(CourseLearnRecordSaveReqVO createReqVO) {
        CourseLearnRecordDO courseLearnRecord = BeanUtils.toBean(createReqVO, CourseLearnRecordDO.class);
        courseLearnRecordMapper.insert(courseLearnRecord);
        return courseLearnRecord.getId();
    }

    @Override
    public void updateCourseLearnRecord(CourseLearnRecordSaveReqVO updateReqVO) {
        validateCourseLearnRecordExists(updateReqVO.getId());
        CourseLearnRecordDO updateObj = BeanUtils.toBean(updateReqVO, CourseLearnRecordDO.class);
        courseLearnRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseLearnRecord(Long id) {
        validateCourseLearnRecordExists(id);
        courseLearnRecordMapper.deleteById(id);
    }

    private void validateCourseLearnRecordExists(Long id) {
        if (courseLearnRecordMapper.selectById(id) == null) {
            throw exception(COURSE_LEARN_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public CourseLearnRecordDO getCourseLearnRecord(Long id) {
        return courseLearnRecordMapper.selectById(id);
    }

    @Override
    public PageResult<CourseLearnRecordDO> getCourseLearnRecordPage(CourseLearnRecordPageReqVO pageReqVO) {
        return courseLearnRecordMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseLearnRecordListByIds(List<Long> ids) {
        ids.forEach(this::validateCourseLearnRecordExists);
        courseLearnRecordMapper.deleteBatchIds(ids);
    }

}
